#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     decorators
   文件功能描述 :   一些装饰器的封装处理
   创建人 :       小钟同学
   创建时间 :          2021/12/14
-------------------------------------------------
   修改描述-2021/12/14:         
-------------------------------------------------
"""
from inspect import iscoroutinefunction
from functools import wraps
import time
import asyncio
from concurrent.futures import ThreadPoolExecutor
import typing as t
import functools
import multiprocessing.pool


def logger_deco(func):
    if func is None:
        return

    @wraps(func)
    def inner(*args, **kwargs):
        code = 'success'
        start_time = time.time()
        handler_call_details = args[2]
        try:
            results = func(*args, **kwargs)
        except Exception as exc:
            code = 'error'
            raise exc
        finally:
            resp_time = round(((time.time() - start_time)) * 1000)
            response = {
                'code': code,
                'resp_time': resp_time
            }
        return results

    return inner


#
def wrapper_evennt_route(**params):
    """
   兼容普通函数和协程函数的装饰器
    """
    def wrapper(func):
        if iscoroutinefunction(func):
            @wraps(func)
            async def decorated(*args, **kwds):
                return await func(*args, **kwds)
        else:
            @wraps(func)
            def decorated(*args, **kwds):
                return func(*args, **kwds)
        return decorated

    return wrapper


def run_sync(coroutine: t.Coroutine):
    """
    同步运行协程程序-----------普通函数转协程函数
    启动新的线程来完成想其他的协同程序的调用
    """
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        return asyncio.run(coroutine)
    else:
        if loop.is_running():
            new_loop = asyncio.new_event_loop()

            with ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(
                    new_loop.run_until_complete, coroutine
                )
                return future.result()
        else:
            return loop.run_until_complete(coroutine)


def timeout(max_timeout: int):
    def timeout_decorator(item):
        @functools.wraps(item)
        def func_wrapper(*args, **kwargs):
            pool = multiprocessing.pool.ThreadPool(processes=1)
            async_result = pool.apply_async(item, args, kwargs)
            return async_result.get(max_timeout)

        return func_wrapper

    return timeout_decorator


def time_cost(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        st = time.time()
        res = func(*args, **kwargs)
        print(f"{func.__name__} cost {round(time.time() - st, 3)}s")
        return res

    return wrapper


import time


@time_cost
def ceshi():
    print("你开始！！")
    time.sleep(5)
    print("你没！！")


if __name__ == '__main__':
    ceshi()
